package br.com.chat.client;

import java.rmi.RMISecurityManager;
import java.util.List;

import br.com.chat.Message;
import br.com.chat.User;
import br.com.chat.rmi.ChatManager;
import br.com.chat.rmi.MessageReceiver;
import br.com.chat.rmi.MessageSender;
import br.com.chat.utils.RemoteUtil;

public class ClientPairMain {
    
    public static void main(String[] args) {
        System.setSecurityManager( new RMISecurityManager() );
        
        new Thread(new ClientRunnable("eberson", "jose")).start();
//        new Thread(new ClientRunnable("sidow", "fabao")).start();
//        new Thread(new ClientRunnable("renan", "dusao")).start();
        new Thread(new ClientRunnable("jose", "eberson")).start();
//        new Thread(new ClientRunnable("fabao", "sidow")).start();
//        new Thread(new ClientRunnable("dusao", "renan")).start();
    }
    
    private static class ClientRunnable implements Runnable{
        private String from;
        private String to;

        public ClientRunnable(String from, String to) {
            super();
            this.from = from;
            this.to = to;
        }

        @Override
        public void run() {
            System.setSecurityManager( new RMISecurityManager() );
            User from = new User(this.from);
            User to = new User(this.to);
            int contador = 0;
            
            try {
                ChatManager manager = RemoteUtil.loadManager();
                if ( !manager.isLoggedIn(from)){
                    manager.login(from);
                }
                
                Thread thread = Thread.currentThread();
                String prefix = "[ " + thread.getName() + " ]: ";
                
                while ( !thread.isInterrupted() ){
                    System.out.println( prefix + "Enviando uma mensagem..." );
                    String content = prefix + "Teste com a mensagem " + contador++;
                    
                    MessageSender sender = RemoteUtil.loadSender();
                    sender.sendMessage(from, to, content);
                    
                    Thread.sleep(2000);
                    
                    System.out.println( prefix + "Recebendo mensagens..." );
                    MessageReceiver receiver = RemoteUtil.loadReceiver();
                    List<Message> receive = receiver.receive(from);
                    
                    if ( receive.size() == 0 ){
                        System.out.println( prefix + "Nenhuma mensagem recebida..." );
                        continue;
                    }
                    
                    for (Message message : receive) {
                        System.out.println( prefix + "Recebido a mensagem: " + message);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
